<template>
  <el-dialog :title="`${isEdit ? '编辑' : '添加'}角色`" :visible="show" @open="handleOpen" @close="handleClose">
    <el-form :model="formMessage" ref="form">
      <el-form-item label="角色名称" prop="name">
        <el-input type="text" v-model="formMessage.name" clearable placeholder="请输入角色名称" />
      </el-form-item>
      <el-form-item label="角色编码" prop="code">
        <el-input type="text" v-model="formMessage.code" clearable placeholder="请输入角色编码" />
      </el-form-item>
      <el-form-item label="角色描述" prop="description">
        <el-input type="textarea" v-model="formMessage.description" placeholder="请输入角色描述" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" :loading="loading" @click="handleConfirm">确定</el-button>
    </div>
  </el-dialog>
</template>

<script lang="ts">
import { Form, Message } from 'element-ui'
import { Vue, Component, Prop, Emit } from 'vue-property-decorator'
import { saveOrUpdate } from '@/services/boss'

@Component
export default class RoleAddUpdate extends Vue {
  @Prop(Boolean) show!: boolean;
  @Prop(Boolean) isEdit!: boolean;
  @Prop(Object) detail?: any;

  private formMessage: any = {
    name: '',
    description: '',
    code: ''
  }

  private loading = false

  handleOpen () {
    if (this.isEdit) {
      for (const key in this.formMessage) {
        this.formMessage[key] = this.detail[key]
      }
    }
  }

  async handleConfirm () {
    try {
      this.loading = true
      const params = Object.assign({}, this.formMessage)
      if (this.isEdit) {
        params.id = this.detail.id
      }
      await saveOrUpdate(params)
      Message.success('操作成功')
      this.handleSuccess()
    } catch (e: any) {
      Message.error(e)
    } finally {
      this.loading = false
    }
  }

  @Emit('success')
  handleSuccess () {
    this.handleClose()
  }

  @Emit('close')
  handleClose () {
    (this.$refs.form as Form).resetFields()
  }
}
</script>

<style scoped>

</style>
